package com.novunda.tool.qrcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author linfeng
 * @since 2016/11/10
 */
public class QRBitBuffer {

    private List<Integer> buffer = new ArrayList<Integer>();
    private int length;

    public QRBitBuffer() {
    }

    public Boolean get(Integer index) {
        Integer bufIndex = Double.valueOf(Math.floor(index / 8)).intValue();
        return ((this.buffer.get(bufIndex) >>> (7 - index % 8)) & 1) == 1;
    }

    public void put(Integer num, Integer length) {
        for (int i = 0; i < length; i++) {
            this.putBit(((num >>> (length - i - 1)) & 1) == 1);
        }
    }

    public void putBit(Boolean bit) {
        Integer bufIndex = Double.valueOf(Math.floor(this.length / 8)).intValue();
        if (this.buffer.size() <= bufIndex) {
            this.buffer.add(0);
        }

        if (bit) {
            Integer val = this.buffer.get(bufIndex);
            val |= (0x80 >>> (this.length % 8));
            this.buffer.set(bufIndex, val);
        }

        this.length++;
    }

    public Integer getLengthInBits() {
        return this.length;
    }

    public List<Integer> getBuffer() {
        return buffer;
    }

    public Integer getLength() {
        return length;
    }
}
